package de.hdu.myjobapp.dao;

import java.sql.Blob;
import java.util.ArrayList;
import java.util.List;


import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import de.hdu.myjobapp.model.Application;
import de.hdu.myjobapp.model.Attachment;
import de.hdu.myjobapp.model.Rating;

public class AttachmentDao extends HibernateDaoSupport {
	
	/**
	 * create a new Attachment
	 */	
	public void create(Application applicationId, String attachmentName, Blob attachmentData){
		Attachment a = new Attachment();
		a.setApplicationId(applicationId);
		a.setAttachmentName(attachmentName);
		a.setAttachmentData(attachmentData);
		save(a);
	}
	
		
	/**
	 * Saves the new recieved Attachment from Method create with hibernate into database
	 */	
	public Attachment save(Attachment att){
		HibernateTemplate template = getHibernateTemplate();
		template.saveOrUpdate(att);
		return att;
	}

	/**
	 * return all existing Attachment
	 */	
	public List<Attachment> findAll(){
		HibernateTemplate template = getHibernateTemplate();
		return template.loadAll(Attachment.class);
	}

	/**
	 * Return an existing Attachment by naming ID
	 */	
	public Attachment findById(int id){
		HibernateTemplate template = getHibernateTemplate();
		return(Attachment) template.get(Attachment.class, id);
	}
	/**
	 * Find all ratings related to a specific Application
	 * TODO - improve process not to read whole sql table
	 */
	public List<Attachment> findAll(Application application){
		HibernateTemplate template = getHibernateTemplate();
		List<Attachment> applicationAttachments = new ArrayList<Attachment>();
		List<Attachment> allattachments = template.loadAll(Attachment.class);
		for(Attachment attachment:allattachments){
			if(attachment.getApplicationId().getApplicationId().equals(application.getApplicationId())){
				applicationAttachments.add(attachment);
			}
		}
		return applicationAttachments;
	}

}
